#include <iostream>

using namespace std;

const int N = 12;
int a[N][N];
bool st[N][N];
bool check[1000];
int n, k;
string path;
int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};
int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1};


void dfs(int cx, int cy)
{
	if(cx == n && cy == n)
	{
		int flag = true;
		for(int i = 1; i <= n; i++)
		{
			for(int j = 1; j <= n; j++)
			{
				if(!st[i][j])
				{
					flag = false;
					break;
				}
			}
		}
		if(flag)
		{
			cout << path << endl;
			exit(0);
		}
		
	}
	for(int k = 0; k < 8; k++)
	{
		int nx = cx + dx[k], ny = cy + dy[k];
		if(nx < 1 || ny < 1 || nx > n || ny > n) continue;
		if(st[nx][ny] || a[nx][ny] != a[cx][cy] + 1) continue;
		if(k == 3 || k == 7)
		{
			int x1 = nx - 1, y1 = ny;
			if(check[x1 + y1]) continue;
			check[x1 + y1] = true;
			st[nx][ny] = true;
			path.push_back(k);
			dfs(nx, ny);
			check[x1 + y1] = false;
			st[nx][ny] = false;
			path.pop_back();	
		}
		else if(k == 1 || k == 5)
		{
			int x1 = nx + 1, y1 = ny;
			if(check[x1 - y1 + n]) continue;
			check[x1 - y1 + n] = true;
			st[nx][ny] = true;
			path.push_back(k);
			dfs(nx, ny);
			check[x1 - y1 + n] = false;
			st[nx][ny] = false;
			path.pop_back();
		}
		else
		{
			path.push_back(k);
			dfs(nx, ny);
			path.pop_back();
		}
	}
}

int main()
{
	cin >> n >> k;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			cin >> a[i][j];
			if(a[i][j] >= k || a[i][j] < 0 || n * n % k != 0) 
			{
				cout << -1 << endl;
				return 0;
			}

		}
	}
	
	dfs(1, 1);
	cout << "-1" << endl;
	return 0;
}
